package com.bp.hearthealth.pulse.lnapps.bp_view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.widget.ImageView
import com.bp.hearthealth.pulse.lnapps.R

class BPCustomSegmentedImageView(context: Context, attrs: AttributeSet? = null) : ImageView(context, attrs) {

    private val segmentColors = arrayOf(
        Color.parseColor("#027FFA"), Color.GREEN, Color.YELLOW, Color.MAGENTA, Color.RED, Color.CYAN
    )

    private val segmentTexts = arrayOf("小于60", "60", "70", "80", "90", "大于100")

    private val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        textAlign = Paint.Align.CENTER
    }

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomSegmentedImageView)
        val textSize = typedArray.getDimensionPixelSize(R.styleable.CustomSegmentedImageView_sctextSize, 16)
        val textColor = typedArray.getColor(R.styleable.CustomSegmentedImageView_sctextColor, Color.BLACK)
        typedArray.recycle()

        // 设置文本属性
        textPaint.textSize = textSize.toFloat()
        textPaint.color = textColor
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        val progress = calculateProgress()

        // 绘制进度条
        drawProgressBar(canvas, progress)

        // 绘制文字
        drawTextBelowProgressBar(canvas, progress)
    }

    private fun drawProgressBar(canvas: Canvas?, progress: Int) {
        val totalSegments = segmentColors.size
        val segmentWidth = width / totalSegments.toFloat()

        for (i in 0 until totalSegments) {
            val left = (i * segmentWidth).toInt()
            val right = ((i + 1) * segmentWidth).toInt()

            val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
                color = segmentColors[i]
            }

            canvas?.drawRect(left.toFloat(), 0f, right.toFloat(), height.toFloat(), paint)
        }
    }

    private fun drawTextBelowProgressBar(canvas: Canvas?, progress: Int) {
        val totalSegments = segmentColors.size
        val segmentWidth = width / totalSegments.toFloat()

        for (i in 0 until totalSegments) {
            val textX = (i * segmentWidth + segmentWidth / 2).toInt()
            val textY = height + textPaint.textSize + 10 // 10是文字和进度条之间的间距

            canvas?.drawText(segmentTexts[i], textX.toFloat(), textY.toFloat(), textPaint)
        }
    }

    private fun calculateProgress(): Int {
        // 根据你的逻辑计算进度，这里假设有一个变量表示进度
        // 请替换成你的实际逻辑
        return 50
    }
}
